<template>
  <div class="search">
    <!-- form 标签用于手机弹出键盘搜索 -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        clearable
        @focus="isResultsShow = false"
      />
    </form>
    <!-- 组件 -->
    <!-- 3.搜索结果 -->
    <!-- 注意顺序很重要 -->
    <search_results
      v-if="isResultsShow"
      :searchText="searchText"
    ></search_results>

    <!-- 2.搜索建议 -->
    <search_suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @getRes="onSearch"
    ></search_suggestion>

    <!-- 1.搜索历史 -->
    <search_history
      v-else
      :searchHistories="searchHistories"
      @historySearch="onSearch"
      @clear="searchHistories = []"
    ></search_history>
  </div>
</template>

<script>
// 导入搜索历史\建议\结果组件
import SeachHistory from './components/search_history'
import SearchResults from './components/search_results'
import SearchSuggestion from './components/search_suggestion'
// 导入本地存储工具
import { setItem, getItem } from '@/utils/storage'

export default {
  name: 'Search',
  components: {
    search_history: SeachHistory,
    search_results: SearchResults,
    search_suggestion: SearchSuggestion
  },
  props: {},
  data() {
    return {
      searchText: '',
      isResultsShow: false,
      searchHistories: getItem('searchHistories') || [] // 搜索历史记录的数组
    }
  },
  created() {},
  mounted() {},
  activited() {},
  update() {},
  beforeRouteUpdate() {},
  methods: {
    onSearch(val) {
      val = val.trim()
      if (!val) return
      // console.log(val)
      this.searchText = val
      // 搜索结果展示之前,将搜索词条存入历史记录数组
      // 效果: 数据不重复,新的在前面
      // 思路: 检测数组中是否包含该词条,不包含,直接添加,包含,删除原数据再添加
      this.searchHistories.forEach((item, i) => {
        if (item === val) {
          this.searchHistories.splice(i, 1)
        }
      })
      this.searchHistories.unshift(val)
      // 内容变为展示搜索结果
      this.isResultsShow = true
    },
    onCancel() {
      // 返回首页
      this.$router.back()
    }
  },
  filter: {},
  computed: {},
  watch: {
    searchHistories(v) {
      // 发生更改,就再存一次
      setItem('searchHistories', v)
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  padding: 108px 0 0;
}
.van-search {
  background-color: #3296fa;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 2;
}
.van-search__action {
  color: #fff;
  font-size: 28px;
}
</style>
